package com.enzo.prms.job.manager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.stereotype.Component;

@Component("jobManager")
public class StoreJobManager implements JobManager  {
	private static final Logger log=Logger.getLogger(StoreJobManager.class);
	private static final String JOB_GROUP_NAME="group1";
	private static final String TRIGGER_GROUP_NAME="trigger1";
	
	@Resource
	private Scheduler scheduler;
	
	public StoreJobManager(){
//		init();
	}

	public void schedulerJob(String jobName,String time,Class<? extends Job> jobClazz) {
		try {
			System.out.println(">>>>>>>>>>>>>"+jobName);
			CronTrigger trigger=(CronTrigger)scheduler.getTrigger(jobName, TRIGGER_GROUP_NAME);
			System.out.println(">>>>>>>>>>>>>"+trigger);
			//更新任务
			if(trigger!=null){
				trigger.setCronExpression(time);
				scheduler.rescheduleJob(jobName, TRIGGER_GROUP_NAME, trigger);
			}else{
				//新建任务
				JobDetail jobDetail=new JobDetail(jobName, JOB_GROUP_NAME, jobClazz);
				jobDetail.getJobDataMap().put("note",jobName);
				trigger=new CronTrigger(jobName, TRIGGER_GROUP_NAME);
				trigger.setCronExpression(time);
				scheduler.scheduleJob(jobDetail, trigger);
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	

	public void schedulerJob(String jobName, Date time,
			Class<? extends Job> jobClazz) {
		Date now=new Date();
		if(time!=null&&time.after(now)){
			String timeStr=parseConExpression(time);
			schedulerJob(jobName, timeStr, jobClazz);
		}else{
			log.info("The job time is before now or null,will not be fired.");
		}
	}

	@Override
	public void schedulerJob(String jobName, String time,
			Map<String, Object> data, Class<? extends Job> jobClazz) {
		try {
			CronTrigger trigger=(CronTrigger)scheduler.getTrigger(jobName, TRIGGER_GROUP_NAME);
			//更新任务
			if(trigger!=null){
				trigger.setCronExpression(time);
				scheduler.rescheduleJob(jobName, TRIGGER_GROUP_NAME, trigger);
			}else{
				//新建任务
				JobDetail jobDetail=new JobDetail(jobName, JOB_GROUP_NAME, jobClazz);
				if(data!=null){
					jobDetail.setJobDataMap(new JobDataMap(data));
				}
				trigger=new CronTrigger(jobName, TRIGGER_GROUP_NAME);
				trigger.setCronExpression(time);
				scheduler.scheduleJob(jobDetail, trigger);
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void schedulerJob(String jobName, Date time,
			Map<String, Object> data, Class<? extends Job> jobClazz) {
		Date now=new Date();
		if(time!=null&&time.after(now)){
			String timeStr=parseConExpression(time);
			schedulerJob(jobName, timeStr, data, jobClazz);
		}else{
			log.info("The job time is before now or null,will not be fired.");
		}
	}

	
	@Override
	public void modifyJobTime(String jobName, String time) {
		try {
			Trigger trigger=scheduler.getTrigger(jobName, TRIGGER_GROUP_NAME);
			if(trigger!=null){
				CronTrigger ct=(CronTrigger)trigger;
				ct.setCronExpression(time);
				/*@SuppressWarnings("unchecked")
				Class<? extends Job> clz=scheduler.getJobDetail(jobName, JOB_GROUP_NAME).getJobClass();
				System.out.println("JobClz====="+clz.getName());
				scheduler.deleteJob(jobName, JOB_GROUP_NAME);
				schedulerJob(jobName, time, clz);*/
				scheduler.rescheduleJob(jobName, TRIGGER_GROUP_NAME, trigger);
//				scheduler.resumeTrigger(jobName, TRIGGER_GROUP_NAME);
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void modifyJobTime(String jobName, Date time) {
		String cronStr=parseConExpression(time);
		modifyJobTime(jobName, cronStr);
	}

	@Override
	public void removeJob(String jobName) {
		try {
			scheduler.pauseTrigger(jobName, TRIGGER_GROUP_NAME);
			scheduler.unscheduleJob(jobName, TRIGGER_GROUP_NAME);
			scheduler.deleteJob(jobName, JOB_GROUP_NAME);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化
	 */
	public void init(){
		log.info("==========RAMJobManager init==========");
		try {
			if(scheduler!=null&&!scheduler.isShutdown()&&!scheduler.isStarted()){
				scheduler.start();
			}else{
				scheduler=new StdSchedulerFactory().getScheduler();
				scheduler.start();
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * format the time to conExpression
	 * @param sendDate
	 * @return
	 */
	private String parseConExpression(Date time){
		if(time!=null){
			SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String val=sf.format(time);
			String year=val.substring(0, 4);
			String month=val.substring(5,7);
			String day=val.substring(8, 10);
			String hour=val.substring(11, 13);
			String minute=val.substring(14);
			return "00"+" "+minute+" "+hour+" "+day+" "+month+" ? "+year;
		}
		return null;
	}

	public Scheduler getScheduler() {
		return scheduler;
	}

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}

}
